```vue
<template>
  <el-container class="recipe-page" style="padding: 20px;">
    <el-header style="font-size: 24px; font-weight: bold;">菜谱搜索</el-header>
    <el-main>
      <!-- 搜索区：区域下拉 + 关键词输入 -->
      <el-row align="middle" gutter="10">
        <el-col :span="6">
          <el-select
            v-model="selectedArea"
            placeholder="选择地区"
            clearable
            @change="searchByArea"
          >
            <el-option
              v-for="area in areas"
              :key="area"
              :label="area"
              :value="area"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input
            v-model="query"
            placeholder="输入菜名或食材"
            clearable
            @keyup.enter="searchByName"
          />
        </el-col>
        <el-col>
          <el-button type="primary" @click="searchByName">搜索</el-button>
        </el-col>
      </el-row>

      <!-- 菜谱列表 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col
          v-for="meal in meals"
          :key="meal.idMeal"
          :xs="24" :sm="12" :md="8" :lg="6"
        >
          <el-card shadow="hover" class="meal-card">
            <img
              :src="meal.strMealThumb"
              class="meal-thumb"
              alt="菜品图片"
            />
            <div class="meal-info">
              <h3>{{ meal.strMeal }}</h3>
              <el-space>
                <el-button text @click="showDetail(meal.idMeal)">查看详情</el-button>
                <el-button text @click="favorite(meal.idMeal)">收藏</el-button>
              </el-space>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 无结果提示 -->
      <div
        v-if="meals.length === 0 && (searchedByName || searchedByArea)"
        class="no-result"
      >
        未找到相关菜谱
      </div>

      <!-- 详情对话框 -->
      <el-dialog
        v-model="dialogVisible"
        width="50%"
        :title="detail.strMeal || '菜谱详情'"
      >
        <div v-if="detail.idMeal">
          <el-image
            :src="detail.strMealThumb"
            fit="cover"
            style="width: 100%; height: 200px; margin-bottom: 10px;"
          />
          <p><strong>类别：</strong>{{ detail.strCategory }}</p>
          <p><strong>地区：</strong>{{ detail.strArea }}</p>
          <h4>原料和用量：</h4>
          <ul>
            <li
              v-for="(ing, idx) in ingredients"
              :key="idx"
            >{{ ing }}</li>
          </ul>
          <h4>做法：</h4>
          <p style="white-space: pre-wrap;">
            {{ detail.strInstructions }}
          </p>
          <div style="margin-top: 10px;">
            <el-link
              v-if="detail.strSource"
              :href="detail.strSource"
              target="_blank"
              >查看来源</el-link
            >
            <el-link
              v-if="detail.strYoutube"
              :href="detail.strYoutube"
              target="_blank"
              >视频教程</el-link
            >
          </div>
        </div>
        <template #footer>
          <el-button text @click="dialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script setup >
import { ref, computed, onMounted, reactive } from 'vue'
import axios from 'axios'
import { useUserStore } from '@/store/islogin'
import { ElMessage } from 'element-plus'
import {addFgFavoriteApi} from '@/api/fgRecipe/index'
const useUser = useUserStore()

// 区域列表与选中状态
const areas = ref([])
const selectedArea = ref('')

// 关键词与搜索状态
const query = ref('')
const searchedByName = ref(false)
const searchedByArea = ref(false)

// 菜谱列表与详情
const meals = ref([])
const detail = ref({})
const dialogVisible = ref(false)

onMounted(async () => {
  const res = await axios.get(
    'https://www.themealdb.com/api/json/v1/1/list.php?a=list'
  )
  areas.value = res.data.meals.map(item => item.strArea)
})

async function searchByArea(area) {
  meals.value = []
  searchedByArea.value = false
  if (!area) return
  const res = await axios.get(
    `https://www.themealdb.com/api/json/v1/1/filter.php?a=${encodeURIComponent(area)}`
  )
  meals.value = res.data.meals || []
  searchedByArea.value = true
}

async function searchByName() {
  meals.value = []
  searchedByName.value = false
  if (!query.value.trim()) return
  const res = await axios.get(
    `https://www.themealdb.com/api/json/v1/1/search.php?s=${encodeURIComponent(query.value)}`
  )
  meals.value = res.data.meals || []
  searchedByName.value = true
}

async function showDetail(id) {
  const res = await axios.get(
    `https://www.themealdb.com/api/json/v1/1/lookup.php?i=${id}`
  )
  detail.value = res.data.meals[0] || {}
  dialogVisible.value = true
}

async function favorite(id) {
  if (!useUser.user) {
    ElMessage.error("请先登录")
    return
  }

  try {
    // 每次调用使用新对象（避免状态残留）
    const params = {
      userId: useUser.user.userId,
      fgreId: id // 建议后端改字段名为 mealId
    }
    
    const res = await addFgFavoriteApi(params) // 直接传必要参数
    
    if (res.code === 200) {
      ElMessage.success(res.msg)
    } else {
      ElMessage.warning(res.msg || '操作失败')
    }
  } catch (err) {
    console.error('收藏失败:', err)
    ElMessage.error('请求异常，请稍后重试')
  }
}

const ingredients = computed(() => {
  if (!detail.value.idMeal) return []
  return Array.from({ length: 20 })
    .map((_, i) => {
      const ing = detail.value[`strIngredient${i + 1}`]
      const measure = detail.value[`strMeasure${i + 1}`]
      return ing ? `${ing} (${measure || ''})` : null
    })
    .filter(Boolean)
})
</script>

<style scoped>
.recipe-page {
  background: #f9f9f9;
  min-height: 100vh;
}
.meal-card {
  margin-bottom: 20px;
  cursor: pointer;
}
.meal-thumb {
  width: 100%;
  height: 150px;
  object-fit: cover;
}
.meal-info {
  padding: 10px;
  text-align: center;
}
.no-result {
  margin-top: 20px;
  text-align: center;
  color: #999;
}
</style>

